const util = require("../../utils/util");

const db = wx.cloud.database();
const _ = db.command;
const db_orders = db.collection('orders');
const db_menuImg = db.collection('menuImg');
const app = getApp()

// pages/extraOrder/extraOrder.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    counterId: '',
    myOrderDate: '',
    imgList: [],

    extraOrderDate: '',
    show: false,
    rooms: ['餐厅001', '餐厅002'],
    indexRoom: 0,
    order: {
      person: '',
      number: '',
      extraOrderDate: '',
      room: '',
      orderType: '1',
      count: 0,
      note: '',
      checked: false,
    },
    orderType: '1',
    count: 0,
    checked: false,
    note: '',
    addHidden: false,
    delHidden: false,

    formatter(day) {
      const month = day.date.getMonth() + 1;
      const date = day.date.getDate();
      if (date === new Date().getDate()) {
        day.bottomInfo = '今天';
      }
      return day;
    }
  },
   //检查订餐时间是否超过范围，可以订餐返回true
   checkOrderTime(d) {
    console.log(util.formatDate(new Date()).time) //午餐
    let currDate = new Date()
    let orderDate = this.data.myOrderDate
    let seven_day =  (orderDate.getTime() - currDate.getTime())/(1000*60*60*24)
   
    if(parseInt(seven_day) >= 7){
      wx.showToast({
        title: '只能提前订一周的餐。',
        icon: 'none'
      })
      return false
    }

    if (this.data.orderType == 1 && this.data.extraOrderDate == util.formatDate(currDate).date_week && currDate.getHours() > 9) {
      wx.showToast({
        title: '已超出订餐时间。',
        icon: 'none'
      })
      return false
    } else if (this.data.orderType == 2 && this.data.extraOrderDate == util.formatDate(currDate).date_week && currDate.getHours() > 12) {
      wx.showToast({
        title: '已超出订餐时间。',
        icon: 'none'
      })
      return false
    } else if (this.data.orderType == 3 && this.data.extraOrderDate == util.formatDate(currDate).date_week && currDate.getHours() > 17) {
      wx.showToast({
        title: '已超出订餐时间。',
        icon: 'none'
      })
      return false
    } else {
      return true
    }

  },
  // 添加订餐记录
  addOrder() {
    if (this.checkOrderTime(this.extraOrderDate)) {
      this.setData({
        count: 1
      });
      db_orders.add({
        data: {
          person: this.data.userInfo.name,
          number: this.data.userInfo.number,
          type: 2,
          extra_order_date: this.data.extraOrderDate,
          room: this.data.rooms[this.data.indexRoom],
          order_type: this.data.orderType,
          order_count: this.data.count,
          note: this.data.note,
          package: this.data.checked
        },
        success: res => {
          console.log("订餐成功", res)
          this.setData({
            counterId: res._id,
            addHidden: true
          });
  
          wx.showToast({
            title: '订餐成功',
            icon: 'none'
          });
          console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
  
        },
        fail: err => {
          wx.showToast({
            title: '订餐失败',
            icon: 'none'
          });
          console.error('[数据库] [新增记录] 失败：', err)
        }
      });
    }
    

  },
  // 删除订餐记录
  delOrder() {
    let id = this.data.counterId;
    if (id.length > 0) {
      console.log(id)
      console.log(this.data.myOrderDate)
      const day = util.checkDay(new Date(),this.data.myOrderDate).day
      console.log(day)
      if(day*24 < 48){
        util.tips('48小时以内的不允许撤餐')
        return false
      }

      db_orders.doc(id).remove()
        .then(res => {
            console.log(res)
            this.setData({
              counterId: '',
              checked: false,
              note: '',
              count: 0,
              addHidden: false
            });
            wx.showToast({
              title: '撤餐成功',
              icon: 'none'
            })
          }

        ).catch(err => {
          wx.showToast({
            title: '撤餐失败',
            icon: 'none'
          });
          console.error('[数据库] [删除记录] 失败：', err)
        });
    } else {
      wx.showToast({
        title: '撤餐无效',
        icon: 'none'
      })
    }
  },
  getMenuImg(callback) {
    return db_menuImg.orderBy('time', 'desc').limit(1).get({
      success: res => {
        console.log(res)
        callback(res)
      }
    });
  },
  getTmpUrl(res) {
    console.log(res.data[0].fileID)
    wx.cloud.getTempFileURL({
      fileList: [res.data[0].fileID],
      success: res => {
        // get temp file URL
        console.log(res.fileList)
        this.setData({
          imgList: [res.fileList[0].tempFileURL]
        });
        console.log('图片',this.data.imgList)
      },
      fail: err => {
        // handle error
      }
    })
  },

  //点击图片
  ViewImage(e) {
    console.log("点击图片", e)
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url,
    });
  },

  onChangeNote(e) {
    // event.detail 为当前输入的值
    console.log(e.detail.value);
    this.setData({
      note: e.detail.value
    })
  },
  onChangePackge(e) {
    this.setData({
      checked: e.detail
    });
  },
  onChangeOrderType(e) {
    this.setData({
      orderType: e.detail,
    });
    console.log(e)
    this.isOrderedByDay(this.data.extraOrderDate,this.data.orderType)
  },
  chooseRoom(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value),
      this.setData({
        indexRoom: e.detail.value
      })
  },

  chooseDate() {
    this.setData({
      show: true
    });
    console.log(this.data.show)
  },
  onDisplay() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  onConfirm(event) {
    this.setData({
      show: false,
      myOrderDate: event.detail,
      extraOrderDate: util.formatDate(event.detail).date_week,
    });
    this.isOrderedByDay(this.data.extraOrderDate);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.getRooms();
    this.getMenuImg(this.getTmpUrl)
    this.setData({
      // userInfo: app.globalData.userInfo,
      userInfo: wx.getStorageSync('userInfo'),
      myOrderDate: new Date(),
      extraOrderDate: util.formatDate(new Date()).date_week
    });
    this.isOrderedByDay(util.formatDate(new Date()).date_week);
    wx.getUserInfo({
      success: function (res) {
        // this.data.user = res.userInfo
        var userInfo = res.userInfo
        var nickName = userInfo.nickName
        var avatarUrl = userInfo.avatarUrl
        var gender = userInfo.gender //性别 0：未知、1：男、2：女
        var province = userInfo.province
        var city = userInfo.city
        var country = userInfo.country
        console.log(userInfo)
      }
    })
  },

  // 获取餐厅
  getRooms() {
    let rooms = []
    db.collection('rooms').get().then(res => {
      // console.log(res.data)
      res.data.forEach(e => {
        rooms.push(e.name)
      });
      this.setData({
        rooms: rooms
      })

    })

    return rooms
  },
  /**
   * 根据日期判断是否已经订餐
   */
  isOrderedByDay(d, orderType) {
    console.log(this.data.extraOrderDate)
    db_orders.where({
      person: this.data.userInfo.name,
      number: this.data.userInfo.number,
      order_type: orderType,
      extra_order_date: this.data.extraOrderDate
    }).get().then(res => {
      console.log(res.data)
      if (res.data.length > 0) {
        this.setData({
          counterId: res.data[0]._id,
          room: res.data[0].room,
          orderType: res.data[0].order_type,
          count: res.data[0].order_count,
          note: res.data[0].note,
          checked: res.data[0].package,
          addHidden: true
        })
      } else {
        this.setData({
          counterId: '',
          count: 0,
          checked: false,
          note: '',
          addHidden: false
        })
      }
    }).catch(err => {
      console.error(err)
    })
  },
  // 转换餐别
  pasrseOrderType(type) {
    switch (type) {
      case '1':
        return '早餐';
      case '2':
        return '午餐';
      case '3':
        return '晚餐';
      default:
        return '未知'
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})